package com.icloud.auth.boot.controller;

import com.icloud.auth.api.vo.Oauth2TokenVo;
import com.icloud.common.core.api.CommonResult;
import com.icloud.common.core.api.ResultCode;
import com.icloud.common.core.constant.AuthConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义Oauth2获取令牌接口
 * Created by im on 2020/7/17.
 */
@RestController
@Api(tags = "认证中心登录认证")
@RequestMapping("/oauth")
public class AuthController {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @ApiOperation("Oauth2获取token")
    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public CommonResult<Oauth2TokenVo> postAccessToken(HttpServletRequest request,
                                                       @ApiParam("授权模式") @RequestParam String grant_type,
                                                       @ApiParam("Oauth2客户端ID") @RequestParam String client_id,
                                                       @ApiParam("Oauth2客户端秘钥") @RequestParam String client_secret,
                                                       @ApiParam("刷新token") @RequestParam(required = false) String refresh_token,
                                                       @ApiParam("登录用户名") @RequestParam(required = false) String username,
                                                       @ApiParam("登录密码") @RequestParam(required = false) String password,
                                                       @ApiParam("扫码登录的Token，仅扫码登录需要传参") @RequestParam(required = false, name = "scan_access_token") String scanAccessToken
    ) throws HttpRequestMethodNotSupportedException {
        try {
            Map<String, String> parameters = new HashMap<>();
            parameters.put("grant_type", grant_type);
            parameters.put("client_id", client_id);
            parameters.put("client_secret", client_secret);
            parameters.putIfAbsent("refresh_token", refresh_token);
            parameters.putIfAbsent("username", username);
            parameters.putIfAbsent("password", password);
            parameters.putIfAbsent("scan_access_token", scanAccessToken);
            OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(request.getUserPrincipal(), parameters).getBody();
            Oauth2TokenVo oauth2TokenVo = new Oauth2TokenVo()
                    .setToken(oAuth2AccessToken.getValue())
                    .setRefreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                    .setExpiresIn(oAuth2AccessToken.getExpiresIn())
                    .setTokenHead(AuthConstant.JWT_TOKEN_PREFIX);
            return CommonResult.success(oauth2TokenVo);
        }catch (InvalidTokenException e) { // 捕获到refresh_token 过期异常
            return CommonResult.failed(ResultCode.REFRESH_TOKEN_EXPIRE);
        }
    }
}
